#include<iostream>
#include<pthread.h>
#include<unistd.h>
int ticket = 100;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void* sellticket(void* arg) 
{
    char* id = (char*)arg;
    while(1)
    {
        pthread_mutex_lock(&mutex);
        if(ticket > 0) 
        {   
            usleep(100);
            //sleep(1);
            ticket--;
            std::cout<<id<<" 剩余票数："<<ticket<<std::endl;
            pthread_mutex_unlock(&mutex);
        }
        else
        {
            pthread_mutex_unlock(&mutex);//这个代码没有会造成死锁。其他线程无法解锁。
            break;
        }
    }
    return (void*)0;
} 

int main()
{
    pthread_t t1, t2, t3;
    pthread_create(&t1,NULL,sellticket, (void*)"thread-1");
    pthread_create(&t2,NULL,sellticket, (void*)"thread-2");
    pthread_create(&t3,NULL,sellticket, (void*)"thread-3");

    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    pthread_join(t3, NULL);
    pthread_mutex_destroy(&mutex);
    return 0;
}
